//
//  CollectionDbManager.m
//  星期6
//
//  Created by 宗镇荣 on 16/2/26.
//  Copyright © 2016年 zzr. All rights reserved.
//

#import "CollectionDbManager.h"
#import "FMDB.h"
#import "CommonDefin.h"

@interface CollectionDbManager() {
    
    FMDatabaseQueue *_dbQueue;
}


@end


@implementation CollectionDbManager

SYNTHESIZE_SINGLETON_FOR_CLASS(CollectionDbManager);

- (instancetype)init {
    
    if (self = [super init]) {
        
        [self createDb];
    }
    return self;
}
- (void)createDb {
    
   
    NSArray *dbArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentPath = dbArray[0];

    NSString *dbPath = [documentPath stringByAppendingPathComponent:@"app.db"];
    QFLog(@"%@", dbPath);
    
    _dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
    [self createTable];
}

- (void)createTable {

     NSString *sql_create = @"CREATE TABLE IF NOT EXISTS AppCollection (appID   integer ,cover_image_url text,  name text)";
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        // 执行非查询语句
        BOOL isSu = [db executeUpdate:sql_create];
        if (isSu) {
            QFLog(@"%@", @"执行建表成功");
        }else{
            
            QFLog(@"%@", @"执行建表失败");
        }
    }];

}

- (void)insetModel:(GoodsModel *)model{
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        // 1. 写sql语句
        NSString *sql_insert = @"insert into AppCollection(appID,cover_image_url,name) values(?,?,?)";
        
        // 2.执行sql语句
        BOOL isSu = [db executeUpdate:sql_insert,model.appID,model.cover_image_url,model.name];
        
        if (isSu) {
            QFLog(@"%@", @"执行sql语句成功");
            NSLog(@"%@",model.name);
        }else {
            
            QFLog(@"%@", @"执行插入语句失败");
        }
    }];
}

- (void)getAllModel:(CompletionBlock1)block{
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        NSString *sql_select = @"select * from AppCollection";
        FMResultSet *rs = [db executeQuery:sql_select];
        
        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        while ([rs next]) {
            
            GoodsModel *model = [[GoodsModel alloc] init];
            model.appID = (NSNumber *)[rs stringForColumn:@"appId"];
            NSLog(@"%@",model.name);
            model.cover_image_url = [rs stringForColumn:@"cover_image_url"];
            model.name = [rs stringForColumn:@"name"];
            [tempArray addObject:model];
        }
        block(tempArray);
    }];
}



@end
